package com.cnhis.drgs.core.xcode.ftl;

import org.apache.commons.lang3.StringUtils;
import com.cnhis.drgs.core.model.Column;
import com.cnhis.drgs.core.model.TableView;
import com.cnhis.drgs.core.util.DateUtil;
import com.cnhis.drgs.core.vo.FreemarkerHandler;
import com.cnhis.drgs.core.xcode.Template;

import java.io.File;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public abstract class FtlTemplate implements Template {

    //模板处理对象
    FreemarkerHandler freemarkerHandler = new FreemarkerHandler("/ftl");

    //项目名称
    private String projectName;
    //基础包名
    private String basePackage;
    //模块名称
    private String mouduleName;
    //是否保留数据库名称
    private boolean reserveSchema;
    //表对象
    private TableView tableView;
    //表的列对象集合
    private List<Column> columns;

    public FtlTemplate(String projectName, String basePackage, String mouduleName, boolean reserveSchema, TableView tableView, List<Column> columns) {
        this.projectName = projectName;
        this.basePackage = basePackage;
        this.mouduleName = mouduleName;
        this.reserveSchema = reserveSchema;
        this.tableView = tableView;
        this.columns = columns;
    }

    public String getProjectName() {
        return projectName;
    }

    public String getBasePackage() {
        return basePackage;
    }

    public String getMouduleName() {
        return mouduleName;
    }

    public TableView getTableView() {
        return tableView;
    }

    public List<Column> getColumns() {
        return columns;
    }

    /**
     * 列名转化成属性名
     *
     * @param columnName
     * @return
     */
    public String getVariableName(String columnName) {
        columnName = columnName.toLowerCase();
        StringBuilder sb = new StringBuilder();
        String[] arr = columnName.split("_");
        for (int i = 0; i < arr.length; i++) {
            String str = arr[i];
            if (i > 0) {
                str = str.substring(0, 1).toUpperCase() + str.substring(1);
            }
            sb.append(str);
        }
        return sb.toString();
    }

    /**
     * 转化成类名形式
     *
     * @param name
     * @return
     */
    public String getClassName(String name) {
        name = name.toLowerCase();
        StringBuilder sb = new StringBuilder();
        String[] arr = name.split("_");
        for (int i = 0; i < arr.length; i++) {
            String str = arr[i];
            if (i == 0 && "t".equals(str)) {
                continue;
            }
            str = str.substring(0, 1).toUpperCase() + str.substring(1);
            sb.append(str);
        }
        return sb.toString();
    }

    /**
     * 表名转化成属性名
     *
     * @param tableName
     * @return
     */
    public String getClassVariableName(String tableName) {
        String className = getClassName(tableName);
        return className.substring(0, 1).toLowerCase() + className.substring(1);
    }

    /**
     * 数据库类型是否是数字
     *
     * @param dataType
     * @return
     */
    public boolean isNumber(String dataType) {
        return "decimal".equals(dataType) || dataType.contains("int");
    }

    /**
     * 数据库类型映射Java类型
     *
     * @param column
     * @return
     */
    public String getJavaType(Column column) {
        String dataType = column.getData_type();
        String columnName = column.getColumn_name();
        String columnType = column.getColumn_type();
        String type;
        if ("enum('Y','N')".equals(columnType)) {
            type = "org.spring.springbootgenerator.core.enums.YesNoEnum";
        } else if ("timestamp".equals(dataType) || "datetime".equals(dataType)) {
            type = "java.util.Date";
        } else if ("decimal".equals(dataType)) {
            type = "java.math.BigDecimal";
        } else if (dataType.contains("int")) {
            if ("id".equals(columnName) || columnName.endsWith("id")) {
                type = "Long";
            } else {
                type = "Integer";
            }
        } else {
            type = "String";
        }
        return type;
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public String getNowTime() {
        return DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
    }

    private Map<String, Object> getParamsMap() {
        Map<String, Object> params = new HashMap<>();
        String tableComment = tableView.getTable_comment();
        if (!StringUtils.isBlank(tableComment) && "表".equals(tableComment.substring(tableComment.length() - 1, tableComment.length()))) {
            tableComment = tableComment.substring(0, tableComment.length() - 1);
        }
        params.put("tableComment", tableComment);
        params.put("schemaName", reserveSchema ? "`" + tableView.getTable_schema() + "`." : "");
        params.put("tableName", tableView.getTable_name());
        params.put("mouduleName", mouduleName);
        params.put("className", getClassName(tableView.getTable_name()));
        params.put("variableName", getClassVariableName(tableView.getTable_name()));
        params.put("columns", columns);
        params.put("basePackage", basePackage);
        params.put("xcode", this);
        return params;
    }

    /**
     * 模板文件路径
     *
     * @return
     */
    public abstract String getTemplateName();

    /**
     * 生成文件路径
     *
     * @return
     */
    public abstract String getOutPutPath();


    public void outPut(Writer writer) {
        freemarkerHandler.output(getTemplateName(), getParamsMap(), writer);
    }

    public String outPutString() {
        return freemarkerHandler.outputString(getTemplateName(), getParamsMap());
    }

    public void outPutFile(File file) {
        freemarkerHandler.outputFile(getTemplateName(), getParamsMap(), file);
    }


}
